<?php
/**
*     @todo: webpower处理数值日志；  webpower会通过sftp推送到服务器
*     @author: huangning
*     @date: 2018年5月18日 上午10:25:48
*/

namespace app\controllers\crontab;

use Yii;
use app\components\EmailMarket;

class GetWebpowerChannelReturnDataController extends \app\base\Controller
{  
    /**
     *    @todo: 邮箱对象
     *    @var:
     */
    private $_emailObj;
    
    /**
    *    @todo: 日志根目录
    *    @var:
    */
    private $_dirPath; 
    
    /**
     *    @todo: webpower数值日志根目录
     *    @var:
     */
    private $_dirFilePath;
    
    /**
     *    @todo: webpower数值日志根目录 -- 已读取
     *    @var:
     */
    private $_dirReadFilePath;
    
    /**
     *    @todo: webpower数值日志根目录 -- 未读取
     *    @var:
     */
    private $_dirUnReadFilePath;
    
    /**
     *    @todo: webpower数值日志根目录 -- 未读取未解压
     *    @var:
     */
    private $_dirUnReadUnzipFilePath;
    
    /**
    *     @todo: 文件目录检测及生成
    *     @date: 2018年5月18日 上午10:48:15
    *     @param: variable
    *     @return:
    */
    public function checkEnvironment(){
        //日志文件根目录
        $this->_dirPath = ROOT_PATH.'/bounces_data';
        //webpower日志文件根目录
        $this->_dirFilePath = ROOT_PATH.'/bounces_data/webpower_data';
        //webpower数值日志根目录 -- 已读取
        $this->_dirReadFilePath = ROOT_PATH.'/bounces_data/webpower_data/read_data';
        //webpower数值日志根目录 -- 未读取
        $this->_dirUnReadFilePath = ROOT_PATH.'/bounces_data/webpower_data/unread_data';
        //webpower数值日志根目录 -- 未读取未解压
        $this->_dirUnReadUnzipFilePath = ROOT_PATH.'/bounces_data/webpower_data/unread_data/unzip';
        
        //检测文件根目录
        if (!file_exists($this->_dirPath) || !is_dir($this->_dirPath)){
            echo ROOT_PATH.'/bounces_data 目录不存在请手动创建';
            exit;
        }
        
        //检测webpower日志文件根目录
        if (!file_exists($this->_dirFilePath) || !is_dir($this->_dirFilePath)){
            mkdir($this->_dirFilePath);
        }
        
        //检测webpower日志文件根目录
        if (!file_exists($this->_dirReadFilePath) || !is_dir($this->_dirReadFilePath)){
            mkdir($this->_dirReadFilePath);
        }
        
        //检测webpower日志文件根目录
        if (!file_exists($this->_dirUnReadFilePath) || !is_dir($this->_dirUnReadFilePath)){
            mkdir($this->_dirUnReadFilePath);
        }
        
        //检测webpower日志文件根目录
        if (!file_exists($this->_dirUnReadUnzipFilePath) || !is_dir($this->_dirUnReadUnzipFilePath)){
            mkdir($this->_dirUnReadUnzipFilePath);
        }

    }
    
    /**
    *     @todo: 解压文件
    *     @date: 2018年5月18日 上午11:08:43
    *     @param: variable
    *     @return:
    */
    public function unZip($filename) 
    {
        try {
            $zip = new \ZipArchive;
            
            if (file_exists($filename)) {
                $res = $zip->open($filename);
                if ($res === TRUE) {
                    $zip->extractTo($this->_dirUnReadUnzipFilePath);
                    $zip->close();
                    return true;
                } else {
                    return false;
                }
            }
        }catch (\Exception $e){
            //ignore    记录日志
            return false;
        }
        
    } 
    
    /**
     *     @todo: 数据解析
     *     @date: 2018年5月18日 上午10:42:46
     *     @param: variable
     *     @return:
     */
    public function actionGetDetailInfo()
    {
        ignore_user_abort(true);
        set_time_limit(0);
    
        //环境检测
        $this->checkEnvironment();
        
        //文件解压
        foreach (glob($this->_dirUnReadFilePath . "/*.zip") as $file){
            try {
                //解压文件
                $fileName = basename($file);
                $upZipFlag = $this->unZip($file);
                //解压成功放入已读里面
                if ($upZipFlag) {
                    rename($file, $this->_dirReadFilePath . '/' . $fileName);
                }

            }catch (\Exception $e){
                //ignore  记录日志
            }            
        }
        
        //文件处理
        foreach (glob($this->_dirUnReadUnzipFilePath . "/*.csv") as $file){
            try {
                $this->dealData($file);       
            }catch (\Exception $e){
                //ignore  记录日志
            }
        }
    }
    
    /**
    *     @todo: 保存数据
    *     @date: 2018年5月18日 下午4:16:16
    *     @param: variable
    *     @return:
    */
    public function saveTraceData($data){
        
        return ;
    }
    
    /**
    *     @todo: 处理文件数据
    *     @date: 2018年5月18日 上午11:43:54
    *     @param: $file文件路径
    *     @return:
    */
    public function dealData($file){
        
        if (!file_exists($file)) {
            return false;
        }
        
        $this->_emailObj = new EmailMarket();
        $reachChannelDataArr = array();
        $allData =  Yii::$app->pubfun->getCSVdata($file);
        $indexName = $allData[0];
        $emailIndex = array_search('email',$indexName);
        $nameIndex = array_search('DMDmailingName',$indexName);
        $typeIndex = array_search('DMDtype',$indexName);
        $logDateIndex = array_search('DMDlogDate',$indexName);
        if ($emailIndex === false || $nameIndex === false || $typeIndex === false || $logDateIndex === false){
            return false;
        }
        array_shift($allData);

        foreach ($allData as $data){
            //分组名称 -- 判断是否是EDM发送的邮件日志
            $groupName = explode('_', $data[$nameIndex]);

            if (count($groupName) != 4){
                continue;
            }
            
            $gid = $groupName[1];
            $channel_id = 9;
            //初始化当前分组的数据
            if (!isset($reachChannelDataArr[$gid])) {
                $reachChannelDataArr[$gid] = [];
                $reachChannelDataArr[$gid]['gid'] = $gid;
                $reachChannelDataArr[$gid]['channel'] = $channel_id;
                $reachChannelDataArr[$gid]['emailSendInfo'] = [];
            }
            
            switch (strtolower($data[$typeIndex])) {
                case 'click':   //点击
                    $email = $this->_emailObj->encryption($data[$emailIndex]);
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['email'] =  $email;
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_click'] = 1;
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['click_time'] = $data[$logDateIndex];                   
                    break;
                case 'hardbounce 1x':   //硬弹
                case 'hardbounce 2x':
                case 'hardbounce final':
                    $email = $this->_emailObj->encryption($data[$emailIndex]);
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['email'] =  $email;
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_hard_bounces'] = 1;
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['bounces_time'] = $data[$logDateIndex];
                    break;
                case 'softbounce 1x':   //软弹
                case 'softbounce 2x':
                case 'softbounce final':
                    $email = $this->_emailObj->encryption($data[$emailIndex]);
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['email'] =  $email;
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_soft_bounces'] = 1;
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['bounces_time'] = $data[$logDateIndex];
                    break;
                case 'unsubscriber':    //取订
                    $email = $this->_emailObj->encryption($data[$emailIndex]);
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['email'] =  $email;
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_unsubscribe'] = 1;
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['unsubscribe_time'] = $data[$logDateIndex];
                    break;
                case 'spamcomplaint':   //投诉
                    $email = $this->_emailObj->encryption($data[$emailIndex]);
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['email'] =  $email;
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['is_complaint'] = 1;
                    $reachChannelDataArr[$gid]['emailSendInfo'][$email]['complaint_time'] = $data[$logDateIndex];
                    break;
            }
        }
        
        // 数据入库        
        $curBjTime = \yii::$app->bjTime->time();

        foreach ($reachChannelDataArr as $reachChannelData){
            $gid = $reachChannelData['gid'];
            // 如果我们网站没有当前分组则不统计
            $groupExistInfoSql =  "select count(*) from mail_group where group_id={$gid}";
            $groupExistInfo = Yii::$app->db->createCommand($groupExistInfoSql)->queryScalar();
            if (!$groupExistInfo) {
                continue;   
            }
            
            foreach ($reachChannelData['emailSendInfo'] as $emailSendInfo){                   
                //获取数据
                $emailType = $this->_emailObj->getEmailType($this->_emailObj->decryption($emailSendInfo['email']));// 邮箱类型
                $email = $emailSendInfo['email'];
                $is_hard_bounces = isset($emailSendInfo['is_hard_bounces']) ? $emailSendInfo['is_hard_bounces'] : 0; // 是否硬弹                  
                $is_soft_bounces = isset($emailSendInfo['is_soft_bounces']) ? $emailSendInfo['is_soft_bounces'] : 0; // 是否软弹                    
                $bounces_time = ($is_hard_bounces || $is_soft_bounces) && isset($emailSendInfo['bounces_time']) ? $this->timeDeal($emailSendInfo['bounces_time']) : 0; // 弹出时间                   
                $bounces_date = $bounces_time ? strstr($bounces_time,' ',true) : '';                   
                $is_complaint = isset($emailSendInfo['is_complaint']) ? $emailSendInfo['is_complaint'] : 0; // 是否投诉                  
                $complaint_time = $is_complaint && isset($emailSendInfo['complaint_time']) ? $this->timeDeal($emailSendInfo['complaint_time']) : 0; // 投诉时间                    
                $complaint_date = $complaint_time ? strstr($complaint_time,' ',true) : '';                    
                $is_unsubscribe = isset($emailSendInfo['is_unsubscribe']) ? $emailSendInfo['is_unsubscribe'] : 0; // 是否退订                   
                $unsubscribe_time = $is_unsubscribe && isset($emailSendInfo['unsubscribe_time']) ? $this->timeDeal($emailSendInfo['unsubscribe_time']) : 0; // 退订时间                   
                $unsubscribe_date = $unsubscribe_time ? strstr($unsubscribe_time,' ',true) : '';                   
                $is_click = isset($emailSendInfo['is_click']) ? $emailSendInfo['is_click'] : 0; // 是否点击                   
                $click_time = $is_click && isset($emailSendInfo['click_time']) ? $this->timeDeal($emailSendInfo['click_time']) : 0; // 点击时间                  
                $click_date = $click_time ? strstr($click_time,' ',true) : '';
                
                $dataArr = array(
                    'is_hard_bounces'   => $is_hard_bounces,
                    'is_soft_bounces'   => $is_soft_bounces,
                    'bounces_time'      => $bounces_time,
                    'bounces_date'      => $bounces_date,
                    'is_complaint'      => $is_complaint,
                    'complaint_time'    => $complaint_time,
                    'complaint_date'    => $complaint_date,
                    'is_unsubscribe'    => $is_unsubscribe,
                    'unsubscribe_time'  => $unsubscribe_time,
                    'unsubscribe_date'  => $unsubscribe_date,
                    'is_click'  => $is_click,
                    'click_time'  => $click_time,
                    'click_date'  => $click_date
                );
                $updateData = [];
                foreach($dataArr as $key => $data){
                    if($data){
                        $updateData[] = "$key = '$data'";
                    }
                }
 
                if(empty($updateData)){
                    continue;
                }
                
                $insertSql = "insert into mail_trace_detail (channel_id,gid,email,email_type,is_hard_bounces,is_soft_bounces,bounces_time,bounces_date,is_complaint,
                complaint_time,complaint_date,is_unsubscribe,unsubscribe_time,unsubscribe_date,is_click,click_time,click_date,add_time) values " ;
                $valuesStr = "({$reachChannelData['channel']},{$gid},'{$email}','{$emailType}',{$is_hard_bounces},{$is_soft_bounces},'{$bounces_time}','{$bounces_date}',
                {$is_complaint},'{$complaint_time}','{$complaint_date}',{$is_unsubscribe},'{$unsubscribe_time}','{$unsubscribe_date}',{$is_click},'{$click_time}',
                '{$click_date}',{$curBjTime}) ON DUPLICATE KEY UPDATE is_deal=0,channel_id={$reachChannelData['channel']},add_time='{$curBjTime}',".join(',',$updateData);
                
                $insertSql .=$valuesStr;
                // 入库
                Yii::$app->db->createCommand($insertSql)->execute();
                
            
            }
            
        }
        
        unlink($file);
        return true;
    }
    
    
    
    /**
    *     @todo: 时间处理函数
    *     @date: 2018年5月18日 上午11:52:03
    *     @param: variable
    *     @return:
    */
    public function timeDeal($timeS) {
        $timeT = \yii::$app->bjTime->strtotime($timeS);
        $timeT = $timeT+8*3600;
        return \yii::$app->bjTime->date('Y-m-d H:i:s',$timeT);
        
    }
    
}

